from sqlalchemy import select

from forward.dependencies.database import db
from forward.model.orm.base import BaseORM
from forward.model.schemas.lucky.merchant import MerchantOutSchema, MerchantSchema
from forward.model.tables.activity import ActivityModel
from forward.model.tables.merchant import MerchantModel


class MerchantORM(BaseORM[
    MerchantOutSchema
]):
    MODEL = MerchantModel
    OUT_SCHEMA = MerchantOutSchema

    @classmethod
    async def get_one_by_activity_id(cls, id: int) -> MerchantOutSchema | None:
        statement = (
            select(MerchantModel)
            .select_from(MerchantModel)
            .join(ActivityModel, ActivityModel.merchant_id == MerchantModel.id)
            .where(ActivityModel.id == id)
        )
        recode = await db.fetch_one(statement)
        if not recode:
            return None
        return MerchantOutSchema.model_validate(recode, from_attributes=True)
